package cn.shafish.colorthings.service;

import cn.shafish.colorthings.pojo.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class HelloSeleniumService {

    private static WebDriver driver;
    WebDriverWait wait;
    Actors actors = new Actors();

    public String sayHello() throws JsonProcessingException {

        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.addArguments("--proxy-server=socks5://127.0.0.1:1080");
        driver = new ChromeDriver(chromeOptions);
        driver.manage().window().maximize();
        List<Works> list = new LinkedList<>();
        wait = new WebDriverWait(driver, 10);

        try {
            String link = "https://javdb.com/actors/4nG3?locale=zh&t=d";
            driver.get(link);
            // 登录

            // 获取当前窗口句柄
            String currentActorHandle = driver.getWindowHandle();
            WebElement videos = driver.findElement(By.id("videos"));
            // 获取演员姓名
            String actorName = driver.findElement(By.className("actor-section-name")).getText();
            // 曾用名或者简介
            String actorIntroduction = driver.findElement(By.className("section-meta")).getText();
            // 演员图片
            String actorImg = driver.findElement(By.className("avatar")).getAttribute("style");

            // 保存
            actors.setLink(link).setIntroduction(actorIntroduction).setName(actorName).setImg(actorImg);

            // 获取作品所在a标签
            List<WebElement> box = videos.findElements(By.className("box"));

            AtomicInteger count = new AtomicInteger();
            JavascriptExecutor jsExecutor = (JavascriptExecutor) this.driver;

            for (WebElement element : box) {
                int i = count.addAndGet(1);
                //String worksImg = element.findElement(By.cssSelector("div > img")).getAttribute("src");
                // 逐个打开页面
                String jsOpenNewWindow = "window.open('" + element.getAttribute("href") + "');";
                jsExecutor.executeScript(jsOpenNewWindow);
                // 切换到该页面
                for (String windowHandle : driver.getWindowHandles()) {
                    if(!currentActorHandle.contentEquals(windowHandle)) {
                        driver.switchTo().window(windowHandle);

                        List<Works> currentData = getCurrentData(list);

                        actors.setWorks(currentData);

                        driver.close();
                        driver.switchTo().window(currentActorHandle);
                    }
                }

                if(i==20) {
                    break;
                }
            }

        } finally {
            driver.quit();
        }

        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(actors);
    }

    public List<Works> getCurrentData(List<Works> list) {
        Works works = new Works();
        // 网址
        String worksHref = driver.getCurrentUrl();
        // 作品图片
        String worksImg = wait.until(driver -> driver.findElement(By.className("video-cover")).getAttribute("src"));
        // 作品名称
        String worksTitle = wait.until(driver -> driver.findElement(By.className("title")).findElement(By.cssSelector("strong")).getText());
        // 作品的其他详细信息对象
        List<WebElement> elements = wait.until(driver -> driver.findElements(By.className("panel-block")));
        String worksNumber, worksTime;
        String score;
        Director director = new Director();
        List<Category> categoryList = new ArrayList<>();
        Series series = new Series();
        for(WebElement element : elements) {
            String value ,flag;
            try {
                value = element.findElement(By.className("value")).getText();
                flag = element.findElement(By.tagName("strong")).getText();
            } catch (Exception e) {
                continue;
            }
            if("番號:".equalsIgnoreCase(flag)) {
                worksNumber = value;
                works.setNumber(worksNumber);
            } else if("日期:".equalsIgnoreCase(flag)) {
                worksTime = value;
                works.setTime(worksTime);
            } else if("導演:".equalsIgnoreCase(flag)) {
                String name = element.findElement(By.cssSelector("span > a")).getAttribute("href");
                String url = element.findElement(By.cssSelector("span > a")).getText();
                director.setName(name).setUrl(url);
                works.setDirector(director);
            } else if("系列:".equalsIgnoreCase(flag)) {
                String name = element.findElement(By.cssSelector("span > a")).getAttribute("href");
                String url = element.findElement(By.cssSelector("span > a")).getText();
                series.setName(name).setUrl(url);
                works.setSeries(series);
            } else if("類別:".equalsIgnoreCase(flag)) {
                List<WebElement> info = element.findElements(By.cssSelector("span > a"));
                for(WebElement item : info) {
                    String url = item.getAttribute("href");
                    String name = item.getText();
                    Category category = new Category();
                    category.setUrl(url).setName(name);
                    categoryList.add(category);
                }
                works.setCategory(categoryList);
            } else if("評分:".equalsIgnoreCase(flag)) {
                score = value;
                works.setScore(score);
            } else if("演員:".equalsIgnoreCase(flag)) {
                List<Map<String, String>> actorsList = new ArrayList<>();
                List<WebElement> info = element.findElements(By.cssSelector("span > a"));
                for(WebElement item : info) {
                    String url = item.getAttribute("href");
                    String name = item.getText();

                    Map<String, String> map = new HashMap<>();
                    map.put("name", name);
                    map.put("url", url);
                    //map.put("gender", );
                    actorsList.add(map);
                }
                works.setParticipants(actorsList);
            }
        }

        works.setImg(worksImg).setHref(worksHref).setTitle(worksTitle);
        list.add(works);
        return list;
    }
}
